using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Viper;

namespace Viper.Opcodes
{
	public class bsr: Instruction
	{
		private string sym;
		private Symbol symb;
		public bsr (string label)
		{
			sym = label;
			this.Mnemonic = "bsr";
			this.Operand = label;
			this.Bytecode = new byte[]{0x10,4,0,0,0,0};
		}
		public bsr(Symbol label)
		{
			symb = label;
			this.Mnemonic = "bsr";
			this.Operand = symb.Name;
			this.Bytecode = new byte[]{0x09,4,0,0,0,0};
		}
		public override void Relocate (ref List<Symbol> symbols)
		{
			int rel = 0;
			if(symb != null)
			{
				rel = (int)(symb.Address - ((int)(this.Address) + 6));
			}
			else
			{
				
				foreach(Symbol s in symbols)
				{
					if(s.Name == sym && s is Label)
					{
						Label lbl = s as Label;
						if(lbl.External)
						{
							Relocation relc = new Relocation();
							relc.RelocationType = 1;
							relc.Symbol = s.Name;
							foreach(Symbol sb in symbols)
							{
								if(sb.Name == s.Name)
								{
									if(!(sb is Label))
									{
										rel = (int)((sb.Address - (this.Address + 6))) ;	
										byte[] val2 = System.BitConverter.GetBytes(rel);
										this.Bytecode = new byte[]{0x10,4,val2[0],val2[1],val2[2],val2[3]};
										return;
									}
								}
							}
							this.RelocData.Add(relc);
							return;
						}
						else
							
						{
							rel = (int)(s.Address - ((int)(this.Address) + 6));
						}
						break;
					}
				}
			}
			byte[] val = System.BitConverter.GetBytes(rel);
			this.Bytecode = new byte[]{0x10,4,val[0],val[1],val[2],val[3]};
		}
	}
}